package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Api(tags = "通用接口")
@RestController
@Slf4j
@RequestMapping("admin/common")
public class CommonController {
    @Autowired
    private AliOssUtil aliOssUtil;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        log.info("原始文件名：{}",originalFilename);
        String url=null;

        try {
            //1,构造参数：字节数组，文件名
            byte[] bytes = file.getBytes();
            //2,获取文件后缀名
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //3,通过UUID生成唯一的文件名，可以防止文件被覆盖
            String objectName= UUID.randomUUID().toString()+suffix;
            //4，调用AliOssUtil工具类，将前端传递的文件保存到阿里云oss
            url=aliOssUtil.upload(bytes,objectName);
        } catch (Exception e) {
           log.error("文件上传失败：{}",e.getMessage());
           return Result.error(MessageConstant.UPLOAD_FAILED);
        }
        //返回图片路径
        return Result.success(url);
    }
}
